//
//  GroupNoticeVC.m
//  AAIM
//
//  Created by awh on 2019/12/14.
//  Copyright © 2019年 AAIM. All rights reserved.
//

#import "GroupNoticeVC.h"
#import "GroupNoticeTableViewCell.h"
#import "ContactRequestLogic.h"
@interface GroupNoticeVC ()<UITableViewDelegate,UITableViewDataSource,GroupNoticeTableViewCellDelegate>
@property (nonatomic,strong)UITableView * groupNoticeTable;
@property (nonatomic,strong)UIView * headView;
@property (nonatomic,copy)NSMutableArray * dataAry;
@property (nonatomic,strong)NSIndexPath * indexPath;

@end

@implementation GroupNoticeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.gk_navTitle=@"群通知";
    [self.view addSubview:self.groupNoticeTable];
    [self getGroupNoticeData];
}

- (void)getGroupNoticeData{
      [self.dataAry removeAllObjects];
  NSArray *groupArray= [[SystemDataBase shareSystemDataBase] queryGroupNoticeMessages];
  NSArray * newAry = [self comparePark:groupArray];
  [self.dataAry addObjectsFromArray:newAry];
  [self.groupNoticeTable reloadData];

}

-(NSArray *)comparePark:(NSArray *)ary

{
  // 时间戳数组(存放时间NSDate对象用于排序)
        NSMutableArray *timeArr = [[NSMutableArray alloc]init];
        // 时间戳-对象字典，将对象和其对应的时间戳字符串存入字典（哈希表）
        NSMutableDictionary *dateKeyArr = [[NSMutableDictionary alloc]init];

        // 2.时间戳取出，并格式化处理
        for(BTMessageModel * model in ary) {
            // 时间戳转成时间对象用于排序
            NSDate  *date = [NSDate dateWithTimeIntervalSince1970:[model.createtime integerValue]];
            [timeArr addObject:date];
            // 时间戳转成时间戳字符串作为key,制作哈希表
            NSNumber *dataNum = [NSNumber numberWithLongLong:[model.createtime integerValue]];
            NSString *datekey = [dataNum stringValue];
            [dateKeyArr setObject:model forKey:datekey];
        }

        // 3.将时间NSDate数组排序
        NSArray *orderedDateArray = [timeArr sortedArrayUsingComparator:^NSComparisonResult(NSDate *date1, NSDate *date2) {
            // 降序排序，最近的时间靠前
                    return [date2 compare:date1];
                    }];

                    // 4.根据排序好的时间数组对号入座将对象按时间排序
                    // 临时数组，保存排序后的对象数组
                    NSMutableArray *sortedAccounts = [[NSMutableArray alloc]init];
                    NSDate *datekey = [[NSDate alloc]init];
                    for (int i = 0; i<orderedDateArray.count; i++) {
                        datekey = orderedDateArray[i];
                        // 日期对象转换成时间戳字符串key
                        NSString *datekeys = [NSString stringWithFormat:@"%lld", (long long)[datekey timeIntervalSince1970]];
                        // 根据时间戳字符串key取对应的对象（哈希表）
                        [sortedAccounts addObject:[dateKeyArr objectForKey:datekeys]];
                    }
              
                return sortedAccounts;
                
            }


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataAry.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    GroupNoticeTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"GroupNoticeCELL"];
    if (!cell) {
        cell = [[GroupNoticeTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"GroupNoticeCELL"];
    }
    cell.delegate=self;
    cell.model=self.dataAry[indexPath.row];
    return cell;
}
-(void)didGroupNoticeTableCell:(GroupNoticeTableViewCell *)groupCell selecedButton:(UIButton *)selecedButton
{
    NSString * isPass;
    selecedButton.tag==100?isPass=@"1":@"2";

        isPass = selecedButton.tag == 100?@"2":@"1";

         groupCell.model.addfriendState=2;
         [[SystemDataBase shareSystemDataBase]updateApplyGroupState:groupCell.model];
         
        // 获取cell的indexPath
       NSIndexPath *indexPath = [self.groupNoticeTable indexPathForCell:groupCell];
        _indexPath = indexPath;
    
        [ContactRequestLogic requestGroupsManagerAuditWithisPass:isPass withUserFuuid:groupCell.model.fuuid joinGroupId:groupCell.model.gId Success:^(NSDictionary * _Nonnull Dict) {
             NSLog(@"同意或者拒绝：%@",Dict);
    
            //        groupCell.acceptBtn.hidden = groupCell.rejectBtn.hidden = YES;
            //        groupCell.statusLbl.hidden = NO;
            //        groupCell.statusLbl.text = selecedButton.tag ==100?@"已拒绝":@"已通过";
            groupCell.model.addfriendState = selecedButton.tag ==100?2:1;
            [[SystemDataBase shareSystemDataBase] updateApplyGroupState:groupCell.model];
            [[UserDataBaseTool shareUserDataBaseTool] reloadData:2 Success:^(BOOL isOK) {
                if (isOK) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:kMessageSystemCreateGroup object:nil];
                }
            }];
           [self getGroupNoticeData];

    } failure:^(NSString * _Nonnull errMsg) {
        [self showTipHudWithText:errMsg];
    }];
}
-(UITableView *)groupNoticeTable{
    if (!_groupNoticeTable) {
        _groupNoticeTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStyleGrouped];
        _groupNoticeTable.delegate = self;
        _groupNoticeTable.dataSource = self;
        _groupNoticeTable.tableFooterView = [UIView new];
        _groupNoticeTable.tableHeaderView = self.headView;
        _groupNoticeTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _groupNoticeTable.rowHeight = UITableViewAutomaticDimension;
        _groupNoticeTable.estimatedRowHeight = 84.f;
        _groupNoticeTable.backgroundColor = KHEXCOLOR(@"#F4F4F4");
    }
    return _groupNoticeTable;
}

-(UIView *)headView{
    if (!_headView) {
        _headView = [[UIView alloc]init];
        _headView.backgroundColor = KHEXCOLOR(@"#F4F4F4");
        _headView.frame=CGRectMake(0, 0, kScreenWidth, 47.f);
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 15, kScreenWidth-30, 17)];
                   label.backgroundColor =  [UIColor clearColor];
           label.font = [UIFont systemFontOfSize:12];
           label.textAlignment=0;
           label.textColor=KHEXCOLOR(@"#BBBBBB");

        label.text = @"验证消息";
        [_headView addSubview:label];
//        _headView.height = 47.f;
    }
    return _headView;
}

-(NSMutableArray *)dataAry{
    if (!_dataAry) {
        _dataAry = [NSMutableArray array];
    }
    return _dataAry;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
